package com.aote.rs;

import java.io.UnsupportedEncodingException;

import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.ContextLoaderListener;

@Path("weixin")
@Singleton
@Component
@Transactional
public class WeiXinService {
	static Logger log = Logger.getLogger(WeiXinService.class);

	/**
	 * 获得授权code
	 */
	@GET
	@Path("test")
	public String test() throws Exception {
		log.debug("sdfhvdsjnvkjdsfn");
		System.out.print("13245678");
		String str = "{\"out_biz_no\":\"{\"order_title\":\"上海交通卡退款\"}}";
		JSONObject h = new JSONObject();
		h.put("timeStamp", "1488514678");
		h.put("appId", "wxb6ee18127275ee6e");
		h.put("pg", "prepay_id=wx201703031218046fcc38b4d90205414165");
		h.put("sign", "23799579AD38F69578992006CA9539DD");
		h.put("signType", "MD5");
		h.put("nonceStr","c460dc0f18fc309ac07306a4a55d2fd6");
		return h.toString();
	}

	/**
	 * 获得授权code
	 */
	@GET
	@Path("getcode")
	public void getcode(@Context HttpServletRequest request,
			@Context HttpServletResponse response) throws Exception {
		WxOpenIdRequest wx = (WxOpenIdRequest) ContextLoaderListener
				.getCurrentWebApplicationContext().getBean("WxOpenIdRequest");
		wx.codeRequest(request, response);
	}

	/**
	 * 获得用户openid
	 * @return 
	 */
	@GET
	@Path("getopenid")
	public  void getopenid(@Context HttpServletRequest request,
			@Context HttpServletResponse response)
			throws UnsupportedEncodingException {
		WxOpenIdRequest wx = (WxOpenIdRequest) ContextLoaderListener
				.getCurrentWebApplicationContext().getBean("WxOpenIdRequest");
		 wx.openidRequest(request, response);
	}

	/**
	 * 获得预下单编号，用于前台调取支付界面
	 * JSONObject
	 */
	@GET
	@Path("getprepayid")
	public String getprepayid(@Context HttpServletRequest request,
			@Context HttpServletResponse response) {
		JSONObject result = new JSONObject();
		WxPrepay wx = (WxPrepay) ContextLoaderListener
				.getCurrentWebApplicationContext().getBean("WxPrepay");
			String h = wx.prePay(request, response).toString();
			log.debug("返回的数据" + h);
		  return h;
	}

	/**
	 * 支付完成回调处理
	 */
	@POST
	@Path("notify")
	public String notify(@Context HttpServletRequest request,
			@Context HttpServletResponse response) throws RuntimeException {
		log.debug("strair-notify");
		JSONObject result = new JSONObject();
		WxPayment wx = (WxPayment) ContextLoaderListener
				.getCurrentWebApplicationContext().getBean("WxPayment");
		wx.pay(request, response);
		log.debug("strair-notify");
		return "SUCCESS";
	}

}
